package com.gofunbuy.app.store;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gofunbuy.R;
import com.gofunbuy.TabStoreGroup;
import com.gofunbuy.core.ProductEntity;
import com.gofunbuy.core.ReceiptEntity;
import com.gofunbuy.http.HttpClientImpl;
import com.gofunbuy.util.GoFunBuyUtils;
import com.gofunbuy.util.SharedPreferencesCompat;
import com.gofunbuy.util.XmlUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SubTabStoreOrderActivity extends Activity {
	
	private EditText mName,mTel1,mTel2,mAddr;
	private CheckBox mIsSaveAddr;
	private Button mCommit;
	LinearLayout mForm;
	TextView mNone;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.store_order_layout);
		
		init();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		String addr = GoFunBuyUtils.getIntPref(this,  "addr", "");
		mAddr.setText(addr);
		if(GoFunBuyUtils.mOrders.size()==0){
			mForm.setVisibility(View.GONE);
			mNone.setVisibility(View.VISIBLE);
		}else{
			mForm.setVisibility(View.VISIBLE);
			mNone.setVisibility(View.GONE);
		}
		addItems();
	}

	private void init(){
		TextView buyList = (TextView) findViewById(R.id.store_topbar_buylist);
		buyList.setVisibility(View.GONE);
		TextView tvTitle = (TextView) findViewById(R.id.store_topbar_title);
		tvTitle.setText(R.string.title_shoping_list);
		
		TextView back = (TextView)findViewById(R.id.store_topbar_back);
		back.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(TabStoreActivity.class,null);
			}			
		});
				
		mForm = (LinearLayout)findViewById(R.id.store_order_form);
		mNone = (TextView)findViewById(R.id.store_order_none);
		
		
		mName = (EditText)findViewById(R.id.store_order_name);
		mTel1 = (EditText)findViewById(R.id.store_order_tel1);
		mTel2 = (EditText)findViewById(R.id. store_order_tel2);
		if(GoFunBuyUtils.mLoginResult!=null){
			mName.setText(GoFunBuyUtils.mLoginResult.name);
			mTel2.setText(GoFunBuyUtils.mLoginResult.tel);			
		}
		
		mAddr = (EditText)findViewById(R.id.store_order_addr);
		mIsSaveAddr = (CheckBox)findViewById(R.id. store_order_save_addr);
		mCommit = (Button)findViewById(R.id. store_order_commit);
		
		mCommit.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String telcode = mTel1.getText().toString().trim();
				String tel = mTel2.getText().toString().trim();
				String name = mName.getText().toString().trim();
				String addr = mAddr.getText().toString().trim();
							
				if(telcode.equals("")){
					Toast.makeText(TabStoreGroup.group, "電話區號不能為空！", 2000).show();
					return;
				}else if(tel.equals("")){
					Toast.makeText(TabStoreGroup.group, "電話號碼不能為空！", 2000).show();
					return;
				}else if(name.equals("")){
					Toast.makeText(TabStoreGroup.group, "姓名區號不能為空！", 2000).show();
					return;
				}else if(addr.equals("")){
					Toast.makeText(TabStoreGroup.group, "地址不能為空！", 2000).show();
					return;
				}
								
				commitOrder(telcode,tel, name, addr, getItems());
			}
			
		});
	}
	private String getItems(){
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		for(int i=0;i<GoFunBuyUtils.mOrders.size();i++){
			if( GoFunBuyUtils.mOrders.get(i).getNum()==0){
				continue;
			}
			sb.append("{\"id\":\""+      GoFunBuyUtils.mOrders.get(i).getPe().getId()          +"\",\"count\":"+     GoFunBuyUtils.mOrders.get(i).getNum()      +" },");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append("]");
		Log.d("yyyy",sb.toString());
		return sb.toString();
	}
	private void addItems(){
		LinearLayout linearItems = (LinearLayout)findViewById(R.id.store_order_items);
		linearItems.removeAllViews();
		for(int i=0;i<GoFunBuyUtils.mOrders.size();i++){
			
			LinearLayout l = new LinearLayout(TabStoreGroup.group);  	
		  	l.setOrientation(LinearLayout.HORIZONTAL);
		  	l.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
		  	l.setPadding(0, 5, 0, 5);
		  	
		  	TextView tv = new TextView(TabStoreGroup.group);
		  	tv.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		  	tv.setPadding(0, 0, 10, 0);
		  	tv.setText(GoFunBuyUtils.mOrders.get(i).getPe().getName());
		  	tv.setMaxWidth(400);
		  	tv.setTextColor(Color.BLACK);
		  	
		  	
		  	Spinner sp = new Spinner(TabStoreGroup.group);
		  	sp.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
		  	ArrayAdapter<String> adapter = new ArrayAdapter<String>(TabStoreGroup.group,android.R.layout.simple_spinner_item,getResources().getStringArray(R.array.store_order_num));  
	        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
	        sp.setAdapter(adapter); 
	        sp.setSelection(GoFunBuyUtils.mOrders.get(i).getNum());
		  	
		  	l.addView(tv);
		  	l.addView(sp);
		  	linearItems.addView(l);
		}	  	
	}
	private void commitOrder(String telcode,String tel,String name,String addr,String items){
		if(mIsSaveAddr.isChecked()){
			GoFunBuyUtils.setIntPref(this, "addr", mAddr.getText().toString().trim()); 
		}
		if(!GoFunBuyUtils.isNetworkConnected(TabStoreGroup.group)){
			Toast.makeText(TabStoreGroup.group, "網絡狀況不好，落單失敗！", 2000).show();
			return;
		}
		String uri = "http://www.eye4gift.com/gofun/app_take_order.php";
		String userId = GoFunBuyUtils.mUserID==null?"0":GoFunBuyUtils.mUserID;	
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("shopcode", "goinside");
		params.put("userid", userId);
		params.put("name", name);
		params.put("telcode", telcode);
		params.put("tel", tel);
		params.put("address", addr);
		params.put("items", items);
		Log.e("888",this.getClass().toString());
		Log.e("888",userId);
		InputStream is = HttpClientImpl.HttpPostData2(uri, params);
		Map<String,String> returns = XmlUtil.getOrderReturn(is);
		
		showProgressDialog(returns);
	}
	private void showProgressDialog(final Map<String,String> returns) {
		if(returns==null){
			return;
		}
		AlertDialog.Builder builder = new Builder(TabStoreGroup.group);  
        builder.setMessage(returns.get("message")==null?"":returns.get("message"));  
        builder.setTitle(returns.get("title")==null?"":returns.get("title"));  
        builder.setPositiveButton("OK",  
        new android.content.DialogInterface.OnClickListener() {  
            @Override  
            public void onClick(DialogInterface dialog, int which) { 
            	 dialog.dismiss();
            	if(returns.get("code")!=null && returns.get("code").equals("1")){
            		GoFunBuyUtils.mOrders.clear();
            		startActivity(TabStoreActivity.class,null);
        		}else {
        			
        		}
            }  
        });  
       
       builder.create().show();	    
	}
	private void startActivity(Class<?> a, Bundle b) {
		// 要跳转的Activity
		// Log.v("名字", a.getSimpleName() + " " + a.getName());
		Intent intent = new Intent(SubTabStoreOrderActivity.this, a);
		if(b!=null){
			intent.putExtras(b);
		}
		
		// 把Activity转换成一个Window，然后转换成View
		Window w = TabStoreGroup.group.getLocalActivityManager().startActivity(
				a.getSimpleName(), intent);
		View view = w.getDecorView();
		// 设置要跳转的Activity显示为本ActivityGroup的内容
		TabStoreGroup.group.setContentView(view);
	}
	
}
